from django.shortcuts import *
from django.http import *
from .models import *
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

def q(func):
    def wrapper(reqeust,*args,**kwargs):
        user = reqeust.COOKIES.get('login')
        if not user:
            return redirect('/')
        return func(reqeust, *args,**kwargs)
    return wrapper
@q
def index(request):
    # if ('login') in request.COOKIES:
    all = Newsinfo.objects.all()
    p= request.GET.get('b')
    resp = HttpResponse()
    print(p)
    if p=='1':
        resp.delete_cookie('login', path='/login/')
    return render(request, 'index.html', {"all": all})

    # return HttpResponseRedirect('/')
@q
# @login_required(login_url='/')
def add(request):
    if request.method == 'GET':
        # if ('login') in request.COOKIES:
            alls = NewsType.objects.all()
            return render(request, 'add.html', {'alls': alls})
        # return HttpResponseRedirect('/')
    else:
        tit = request.POST.get('tit')
        ath = request.POST.get('ath')
        cont = request.POST.get('cont')
        ns = request.POST.get('ns')
        n = request.POST.get('n')
        adds = Newsinfo(tit=tit, ath=ath, cont=cont, ns=ns, NewsType_id=n)
        adds.save()
        return redirect(reverse('index'))


def delete(request, id):
    dele = Newsinfo.objects.filter(pk=id)
    dele.delete()
    return redirect(reverse('index'))


def login(request):
    if request.method == 'GET':
        if ('login') in request.COOKIES:
            li = request.COOKIES.get('login').split(',')
            a = li[0]
            b = li[1]
            return render(request, 'login.html', {'a': a, 'b': b})
        return render(request, 'login.html')
    else:
        uname = request.POST.get('uname')
        pwd = request.POST.get('pwd')
        a = User.objects.filter(uname=uname, pwd=pwd).values('uname')
        resp = HttpResponse()
        e = request.POST.get('e')
        if a:
            if e == '1':
                for i in a:
                    b = i['uname']
                    request.session['user'] = b
                    resp = redirect(reverse('index'))
                    resp.set_cookie('login', uname + ',' + pwd, max_age=60)
                    return resp
            else:
                resp.delete_cookie('login', path='/login/')
                resp = redirect(reverse('index'))
            resp.delete_cookie('login', path='/login/')
        else:
            return HttpResponse('用户名密码错误')
        return resp
        #     return JsonResponse({'flag':1})
        # return JsonResponse({'flag':0})
